package org.advanced.nio;

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author John.zhang
 * @version Id: MMAP, v 1.0 2020/12/15 16:15 ZhiYong Exp $
 * 建立内核区与用户去的内存映射，实现零拷贝
 */
public class Mmap {

    public static void main(String[] args) {

        //通过FileChannel直接建立通道
        try {
            FileChannel inputChannel = FileChannel.open(Paths.get("C:/data/io/io.txt"), StandardOpenOption.READ);
            FileChannel outputChannel = FileChannel.open(Paths.get("C:/data/io/io_cp.txt"), StandardOpenOption.READ, StandardOpenOption.CREATE, StandardOpenOption.WRITE);

            MappedByteBuffer inputMappedByteBuffer = inputChannel.map(FileChannel.MapMode.READ_ONLY, 0, inputChannel.size());
            MappedByteBuffer outputMappedByteBuffer = outputChannel.map(FileChannel.MapMode.READ_WRITE, 0, inputChannel.size());

            byte[] bytes = new byte[inputMappedByteBuffer.limit()];
            inputMappedByteBuffer.get(bytes);
            outputMappedByteBuffer.put(bytes);

            inputChannel.close();
            outputChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
